package com.liuceng.zen.web.auth.utils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

public class Pageable implements Serializable {
  private static final long serialVersionUID = -3930180379790344299L;

  /** 默认页码 */
  private static final int DEFAULT_PAGE_NUMBER = 1;

  /** 默认每页记录数 */
  private static final int DEFAULT_PAGE_SIZE = 50;

  /** 最大每页记录数 */
  private static final int MAX_PAGE_SIZE = 1000;

  private PageBounds pageBounds;
  private List<Order> orders;
  private String searchProperty;
  private String searchValue;
  private String orderProperty;
  private String orderDirection;
  private Integer searchTimeValue;
  private Map<String, Object> filterMap = new HashMap<>();


  /**
   * 构造方法
   */
  public Pageable() {
    this(DEFAULT_PAGE_NUMBER, DEFAULT_PAGE_SIZE, "updated_at", "desc");
  }

  public Pageable(Integer limit) {
    this(DEFAULT_PAGE_NUMBER, limit, "updated_at", "desc");
  }

  /**
   * 构造方法
   * 
   * @param pageNumber 页码
   * @param pageSize 每页记录数
   */
  public Pageable(Integer pageNumber, Integer pageSize) {
    this(pageNumber, pageSize, "updated_at", "desc");
  }

  public Pageable(Integer pageNumber, Integer pageSize, String orderProperties, String order) {
    int curPageNumber = (pageNumber != null && pageNumber >= 1) ? pageNumber : DEFAULT_PAGE_NUMBER;
    int curPageSize = (pageSize != null && pageSize >= 1 && pageSize <= MAX_PAGE_SIZE) ? pageSize
        : DEFAULT_PAGE_SIZE;
    String orderP = StringUtils.isNotBlank(orderProperties) ? orderProperties : "updated_at";
    order = StringUtils.isNoneBlank(order) ? order.trim().toLowerCase() : "";
    String orderB = "asc".equals(order.toLowerCase()) ? "asc" : "desc";
    List<Order> orders = Arrays.asList(Order.create(orderP, orderB));
    //
    this.pageBounds = new PageBounds(curPageNumber, curPageSize, orders);
  }


  /**
   * 获取页码
   * 
   * @return 页码
   */
  public int getPageNumber() {
    return pageBounds.getPage();
  }

  /**
   * 设置页码
   * 
   * @param pageNumber 页码
   */
  public void setPageNumber(int pageNumber) {
    if (pageNumber < 1) {
      pageNumber = DEFAULT_PAGE_NUMBER;
    }
    pageBounds.setPage(pageNumber);
  }

  /**
   * 获取每页记录数
   * 
   * @return 每页记录数
   */
  public int getPageSize() {
    return pageBounds.getLimit();
  }

  /**
   * 设置每页记录数
   * 
   * @param pageSize 每页记录数
   */
  public void setPageSize(int pageSize) {
    if (pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
      pageSize = DEFAULT_PAGE_SIZE;
    }
    pageBounds.setLimit(pageSize);
  }

}
